﻿using System.Linq;
using CardPlay.Model.CardModel;
using CardPlay.Model.GameModel;
using CardPlay.Model.GameModel.Actions;

namespace CardPlay.DemoPack.Games.FreeCellVariants
{
    [Game("EA3A8944-A889-4D2D-83B3-A1043907AE51", LevelOfDifficulty.Easy, LevelOfSkill.MostlySkill, DurationOfPlay.Within5To10Minutes, Family = FamilyName)]
    public class Stalactites : BakersGame
    {
        public Stalactites()
        {
            TotalTableaus = 8;
            TotalReserves = 2;
        }

        protected override IDealAction CreateDealScript()
        {
            var script = new DealScript();

            foreach (var pile in PilesNamed(AnyFoundation).Select(pile => pile.Name))
                script.Deal("1 up").To(pile);

            foreach (var pile in PilesNamed(AnyTableau).Select(pile => pile.Name))
                script.Deal("6 up").To(pile);

            return script.Compile();
        }

        protected override void OverridePlayingRules(PlayingRules rules)
        {
            rules.At(AnyTableau)
                .Revert<MovePileAction>()
                .Permit<RemovePileAction>().When(Action.IsActingOnFaceUpTopCard);
        }

        protected override bool AllowedToBuildFoundation(MovePileAction action)
        {
            if (action.TargetPile.Count == CardFace.RanksPerSuit) return false;

            var difference = RankSequence.AscendingDifference(action.TargetPile.TopCard.Rank, action.PileBeingMoved.BottomCard.Rank);
            var builtFoundation = PilesNamed(AnyFoundation).FirstOrDefault(pile => pile.Count > 1);

            return builtFoundation == null
                ? (difference == 1 || difference == 2)
                : (difference == RankSequence.AscendingDifference(builtFoundation.BottomCard.Rank, builtFoundation.CardAt(1).Rank));
        }
    }
}